<template>
  <div class="product-divide-container">
    <BasicInformation title="修改产品拆卸" :primary-actions="actions" @action="handleAction" />

    <el-form :model="form" :rules="rules" ref="formRef" label-width="120px" class="form-wrapper">
      <!-- 基础信息 -->
      <el-card class="form-section">
        <template #header>
          <span class="section-title">基础信息</span>
        </template>
        <el-row :gutter="30">
          <el-col :md="8">
            <el-form-item label="编号" prop="code">
              <el-input v-model="form.code" disabled />
            </el-form-item>
          </el-col>
          <el-col :md="8">
            <el-form-item label="拆卸日期" prop="date">
              <el-date-picker
                v-model="form.date"
                type="date"
                value-format="YYYY-MM-DD"
                :disabled-date="disabledDate"
              />
            </el-form-item>
          </el-col>
          <!-- 业务员 -->
<el-col :md="8">
  <el-form-item label="业务员" prop="uid">
    <el-select
      v-model="form.uid"
      placeholder="请选择业务员"
      style="width: 240px"
      clearable
      filterable
    >
      <el-option
        v-for="user in userList"
        :key="user.id"
        :label="user.name"
        :value="user.id"
      />
    </el-select>
  </el-form-item>
</el-col>

<!-- 库管员 -->
<el-col :md="8">
  <el-form-item label="库管员" prop="skid">
    <el-select
      v-model="form.skid"
      placeholder="请选择库管员"
      style="width: 240px"
      clearable
      filterable
    >
      <el-option
        v-for="user in userList"
        :key="user.id"
        :label="user.name"
        :value="user.id"
      />
    </el-select>
  </el-form-item>
</el-col>

<!-- 部门 -->
<el-col :md="8">
  <el-form-item label="部门" prop="did">
    <el-select
      v-model="form.did"
      placeholder="请选择部门"
      style="width: 240px"
      clearable
      filterable
    >
      <el-option
        v-for="dept in deptList"
        :key="dept.id"
        :label="dept.name"
        :value="dept.id"
      />
    </el-select>
  </el-form-item>
</el-col>
        </el-row>
      </el-card>

      <!-- BOM 信息 -->
      <el-card class="form-section">
        <template #header>
          <div class="section-header">
            <span class="section-title">BOM 信息</span>
            <el-button type="primary" size="small" @click="bomDialogVisible = true">选择 BOM</el-button>
          </div>
        </template>
        <div v-if="bomDetails">
          <el-row :gutter="20">
            <el-col :md="8"><el-form-item label="BOM 编号"><span>{{ bomDetails.id }}</span></el-form-item></el-col>
            <el-col :md="8"><el-form-item label="BOM 名称"><span>{{ bomDetails.name }}</span></el-form-item></el-col>
            <el-col :md="8"><el-form-item label="产品名称"><span>{{ bomDetails.product.name }}</span></el-form-item></el-col>
          </el-row>
          <el-form-item label="产品仓库" prop="sids[0]">
            <el-select v-model="form.sids[0]" placeholder="请选择产品仓库" clearable>
              <el-option v-for="wh in warehouses" :key="wh.id" :label="wh.name" :value="wh.id" />
            </el-select>
          </el-form-item>
        </div>
        <div v-else>
          <el-alert title="请先选择 BOM 后，再进行物料配置" type="info" show-icon />
        </div>
      </el-card>

      <!-- 商品清单 & 拆卸数量 -->
      <el-card class="form-section">
        <template #header>
          <span class="section-title">商品清单 & 拆卸数量</span>
        </template>
        <el-form-item label="拆卸数量" prop="count">
          <el-input-number v-model.number="form.count" :min="1" @change="onCountChange" style="width:100%" />
        </el-form-item>
        <el-table v-if="bomDetails" :data="[bomDetails.product]" border style="width:100%">
          <el-table-column prop="code" label="商品编码" />
          <el-table-column prop="name" label="商品名称" />
          <el-table-column prop="tax" label="税率" />
          <el-table-column label="即时库存">
            <template #default>
              {{ stocks[0] || 0 }}
            </template>
          </el-table-column>
          <el-table-column label="仓库">
            <template #default>
              <el-select v-model="form.sids[0]" placeholder="请选择仓库" clearable>
                <el-option v-for="wh in warehouses" :key="wh.id" :label="wh.name" :value="wh.id" />
              </el-select>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </el-form>

    <!-- BOM 选择对话框 -->
    <BOMSelectorDialog v-model:modelValue="form.bid" v-model:visible="bomDialogVisible" />
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, computed, watch, onMounted } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import type { ProDivide, BOM } from '@/types/kc/CPCX'
import BasicInformation from '@/public-view/BasicInformation.vue'
import BOMSelectorDialog from '@/basic-view/bom/BOMSelectorDialog.vue'
import request from '@/util/request'
import { useRoute } from 'vue-router'
import type {User} from "@/types/rs/User.ts";
import type {Department} from "@/types/rs/Department.ts";
import type {Store} from "@/types/basic/store.ts";

const route = useRoute()
const code = route.params.code as string
const isEdit = ref(false)


// 获取用户列表（业务员 + 库管员共用）
let userList = ref<User[]>([])
let selectUser = async () => {
  let response = await request.post('per/user/getAll')
  userList.value = response.data.data
  console.log(userList.value)
}
selectUser()

// 获取部门列表
let deptList = ref<Department[]>([])
let selectDept = async () => {
  let response = await request.post('per/dept/getAll')
  deptList.value = response.data.data
  console.log(deptList.value)
}
selectDept()

const userInfo = sessionStorage.getItem('user');
const user = userInfo ? JSON.parse(userInfo) : null;


const form = reactive<Partial<ProDivide>>({
  id: 0,
  code: '',
  bid: 0,
  count: 1,
  uid: 0,
  did: 0,
  skid: 0,
  sids: [],
  date: new Date(),
  typeId: 10,
  createUser: user.user.name,
  updateUser: user.user.name,
})
const formRef = ref<FormInstance>()
const warehouses = ref<{ id: number; name: string }[]>([])
const bomDialogVisible = ref(false)
const bomDetails = ref<BOM | null>(null)
const stocks = ref<number[]>([])

const disabledDate = (time: Date) => time.getTime() > Date.now()

const rules = reactive<FormRules>({
  code: [{ required: true, message: '编号不能为空', trigger: 'blur' }],
  date: [{ required: true, message: '请选择日期', trigger: 'change' }],
  uid: [{ required: true, message: '请输入用户ID', trigger: 'blur' }],
  skid: [{ required: true, message: '请输入仓管人ID', trigger: 'blur' }],
  did: [{ required: true, message: '请输入部门ID', trigger: 'blur' }],
  bid: [{ required: true, message: '请选择 BOM', trigger: 'change' }],
  count: [
    { required: true, message: '请输入拆卸数量', trigger: 'blur' },
    {
      validator(_, v, cb) {
        if (v <= 0) return cb(new Error('拆卸数量必须大于0'))
        if (stocks.value.length > 0 && v > stocks.value[0]) {
          return cb(new Error(`拆卸数量不能超过产品库存：${stocks.value[0]}`))
        }
        cb()
      },
      trigger: 'blur',
    },
  ],
})

async function fetchProductStockOnly() {
  if (!bomDetails.value) return
  const product = bomDetails.value.product
  const sid = form.sids[0]
  if (!sid || !product?.id) {
    stocks.value = [0]
    return
  }
  const r = await request.get('kc/StoreGoodSummary/selectKcStoreGoodBySidCid', {
    params: { sid, gid: product.id },
  })
  stocks.value = [r.data.data?.stock || 0]
}

function onCountChange() {
  formRef.value?.validateField('count')
  fetchProductStockOnly()
}

onMounted(async () => {
  // 加载基础数据和单号
  const [userRes, deptRes, whRes, codeRes] = await Promise.all([
    request.post('per/user/getAll'),
    request.post('per/dept/getAll'),
    request.get('basic/store/getAllStore'),
    request.post('xs/counter/addCode', { docType: 'CPCX' }), // 拆卸单据类型
  ])
  warehouses.value = whRes.data.data
  form.code = codeRes.data.data

  if (code) {
    isEdit.value = true
    // 回显接口，严格用你给的路径和参数
    const res = await request.get('kc/proDivide/getOneProDivide', {
      params: { code },
    })
    const data = res.data.data
    console.log(data)
    Object.assign(form, { ...data, date: data.date })

    // 加载BOM详情
    const bomRes = await request.get('basic/BOM/getBOMById', {
      params: { id: data.bid },
    })
    bomDetails.value = bomRes.data.data

    // 只查产品库存
    await fetchProductStockOnly()
  }
})

watch(
  () => form.bid,
  async (newId) => {
    if (!isEdit.value) {
      form.sids = []
      stocks.value = []
      bomDetails.value = null
    }
    if (newId) {
      try {
        const res = await request.get('basic/BOM/getBOMById', { params: { id: newId } })
        bomDetails.value = res.data.data
        if (!isEdit.value) {
          form.sids = [0]
        }
        await fetchProductStockOnly()
      } catch {
        ElMessage.error('加载BOM详情失败')
      }
    }
  },
  { immediate: true }
)

watch(
  () => form.sids[0],
  async () => {
    await fetchProductStockOnly()
  },
  { immediate: true }
)

const actions = [
  { name: 'save', label: '保存', type: 'primary' },
  { name: 'reset', label: '重置', type: 'warning' },
]

function handleAction(act: string) {
  if (act === 'save') submitForm()
  else resetForm()
}

async function submitForm() {
  await formRef.value?.validate()
  const api = isEdit.value ? 'updateProDivide' : 'addProDivide'
  const res = await request.post(`kc/proDivide/${api}`, JSON.parse(JSON.stringify(form)))
  if (res.data.code == 200) ElMessage.success(res.data.message || (isEdit.value ? '修改成功' : '添加成功'))
  else ElMessage.error(res.data.message || '操作失败')
}

function resetForm() {
  formRef.value?.resetFields()
  Object.assign(form, {
    id: 0,
    code: '',
    bid: 0,
    count: 1,
    uid: 0,
    did: 0,
    skid: 0,
    sids: [],
    date: new Date(),
    typeId: 10,
  })
  isEdit.value = false
  bomDetails.value = null
  stocks.value = []
  ElMessage.info('表单已重置')
}
</script>

<style scoped>
.product-divide-container {
  padding: 20px;
}
.form-section {
  margin-bottom: 20px;
}
.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.section-title {
  font-size: 16px;
  font-weight: 600;
}
.form-wrapper {
  max-width: 800px;
  margin: auto;
}
.mt-4 {
  margin-top: 1rem;
}
</style>

